from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    """ 用户额外信息表，和django自带的用户表关联 """
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # 用户昵称
    nickname = models.CharField(max_length=30, blank=True)
    # 微信公众号唯一标识
    openid = models.CharField(max_length=64, blank=True)
    # 微信开放平台唯一标识
    unionid = models.CharField(max_length=64, blank=True)
    # 用户等级(普通用户为0, 管理员为2, 高级用户为9）
    level = models.IntegerField(default=0)
    # 用户权限(64位长的数字)，按位表示用户权限
    permission = models.BigIntegerField(default=0)
    # 用户头像地址
    avatar = models.CharField(max_length=500, blank=True)
    # 用户性别
    gender = models.IntegerField(default=0)
    # 国家
    country = models.CharField(max_length=32, blank=True)
    # 省份
    province = models.CharField(max_length=32, blank=True)
    # 城市
    city = models.CharField(max_length=32, blank=True)
    # 手机号码
    mobile = models.CharField(max_length=11, blank=True)


class App(models.Model):
    """ GM管理的APP表，一个GM可以管理多个APP """
    # GM id
    gm_id = models.IntegerField(default=0)
    # APP 的Bundle Id
    app_bundle_id = models.CharField(max_length=32, blank=True)
    # 是否启用(0:不启用，1:启用)
    enable = models.IntegerField(default=0)

    class Meta:
        indexes = [
            models.Index(fields=['gm_id'], name='idx_gm_id'),
        ]


class Guild(models.Model):
    """ GM管理的Guild表，一个GM可以管理多个Guild """
    # GM id
    gm_id = models.IntegerField(default=0)
    # Guild 的Bundle Id
    guild_id = models.IntegerField(default=0)
    # 是否启用(0:不启用，1:启用)
    enable = models.IntegerField(default=0)

    class Meta:
        indexes = [
            models.Index(fields=['gm_id'], name='idx_gm_id'),
            models.Index(fields=['guild_id'], name='idx_guild_id'),
        ]


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

